package com.sc.caselist.logic;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sc.caselist.mapper.CaseMapper;
import com.sc.caselist.mapper.LesionMapper;
import com.sc.caselist.service.vo.CaseVO;
import com.sc.caselist.service.vo.ImageVO;
import com.sc.caselist.service.vo.LesionVO;
import com.sc.login.logic.UserLogic;
import com.sc.login.service.vo.UserVO;
import com.sc.user.logic.MarkLogic;
import com.sc.user.mapper.MarkMapper;
import com.sc.utils.*;
import com.sc.utils.entity.*;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Component
public class CaseLogic {

    @Autowired
    private LesionLogic lesionLogic;

    @Autowired
    private ImageLogic imageLogic;

    @Autowired
    private UserLogic userLogic;

    @Autowired
    private MarkMapper markMapper;

    @Autowired
    private CaseMapper caseMapper;

    @Autowired
    private LesionMapper lesionMapper;


    /**
     * 新增单个病例
     */
    @Transactional
    public String insertCase(CaseVO caseVO, UserVO userVO){
        List<LesionVO> lesionVOs=caseVO.getLesionVOs();
//        List<ImageVO> imageVOs=caseVO.getImageVOs();
        CaseEntity entity = MapToBean.toBean(caseVO, CaseEntity.class);
        String caseId = CommonUtils.getUUID();
        entity.setCaseId(caseId);
        entity.setCreatorId(userVO.getUserId());
        entity.setCreatorName(userVO.getUserName());
        entity.setIsDel(TypeEnum.IS_DEL.NO.toString());
        caseMapper.insertCase(entity);

//        lesionLogic.insertLesions(lesionVOs,userVO,caseId);
//        imageLogic.saveImageInfo(imageVOs,userVO);
        return caseId;
    }

    /**
     * 新增或修改单个病例
     */
    @Transactional
    public String saveCase(CaseVO caseVO, String userId){
        UserEntity user = userLogic.findUserByUserId(userId);
        List<LesionVO> lesionVOs=caseVO.getLesionVOs();
        List<ImageVO> caseImageVOs=caseVO.getCaseImageVO();
        List<ImageVO> labelImageVOs=caseVO.getLabelImageVO();
        List<ImageVO> imageVOs = new ArrayList<>();
        for(ImageVO vo:caseImageVOs){
            imageVOs.add(vo);
        }
        for(ImageVO vo:labelImageVOs){
            imageVOs.add(vo);
        }
        //建立文件夹
//        String path="I:/QIUJIAJUN/WBBI/DATAFILE/Images/"+caseVO.getCaseTitle();
        String path="C:/CYT/code/image/"+caseVO.getCaseTitle();
        //判断该路径是否存在
        File file = new File(path);
        if (!file.exists()) {
            //如果这个文件夹不存在的话,就创建这个文件
            file.mkdirs();
        }
        //转移文件
        for(ImageVO vo:imageVOs){
            File startFile = new File("C:/CYT/code/image/"+vo.getImageName());
//            File startFile = new File("I:/QIUJIAJUN/WBBI/DATAFILE/Images/"+vo.getImageName());
            //目的文件路径=目的目录路径+源文件名称
            if(vo.getResourceType().equals(TypeEnum.RESOURCE_TYPE.LESION.toString())){
                File endFile=new File(file+ File.separator+ "label.png");
                startFile.renameTo(endFile);
            }else{
                File endFile=new File(file+ File.separator+ caseVO.getCaseTitle()+".png");
                startFile.renameTo(endFile);
            }
        }
        String caseId = caseVO.getCaseId();
        String caseTitle = caseVO.getCaseTitle();
        if(CommonUtils.isNull(caseId)){
            caseId = CommonUtils.getUUID();
            CaseEntity entity = MapToBean.toBean(caseVO, CaseEntity.class);
            entity.setCaseId(caseId);
            entity.setCreatorId(user.getUserId());
            entity.setCreatorName(user.getUserName());
            entity.setIsSample(TypeEnum.IS_SAMPLE.NO.toString());
            entity.setIsDel(TypeEnum.IS_DEL.NO.toString());
            caseMapper.insertCase(entity);
            lesionLogic.insertLesions(lesionVOs,user,caseId);
            imageLogic.saveImageInfo(imageVOs,user,caseId,caseTitle);
        }else {
            CaseEntity entity = MapToBean.toBean(caseVO, CaseEntity.class);
            entity.setCreatorId(user.getUserId());
            entity.setCreatorName(user.getUserName());
            caseMapper.updateByKey(entity);
            lesionLogic.updateLesions(lesionVOs,user,caseId);
            imageLogic.saveImageInfo(imageVOs,user,caseId,caseTitle);
        }
        return caseId;
    }

    /**
     * 修改单个病例
     */
    @Transactional
    public int updateCase(CaseVO caseVO, UserVO userVO){
        List<LesionVO> lesionVOs=caseVO.getLesionVOs();
        CaseEntity entity = MapToBean.toBean(caseVO, CaseEntity.class);
        entity.setCreatorId(userVO.getUserId());
        entity.setCreatorName(userVO.getUserName());
        entity.setUpdateTime(CommonUtils.getNow());
        caseMapper.updateByKey(entity);

//        return lesionLogic.updateLesions(lesionVOs,userVO,entity.getCaseId());
        return 0;
    }


    /**
     * 删除单个病例
     */
    @Transactional
    public int deleteCase(String caseId){
        CaseEntity entity = new CaseEntity();
        entity.setCaseId(caseId);
        entity.setUpdateTime(CommonUtils.getNow());
        entity.setIsDel(TypeEnum.IS_DEL.YES.toString());
        return caseMapper.updateByKey(entity);
    }

    /**
     * 获取病例列表
     */
    public List<CaseVO> findCaseList(Page<CaseVO> page,String userId,
                                     String keywords){
        CaseEntity entity = new CaseEntity();
        entity.setClinicalHistory(keywords);
        entity.setIsDel(TypeEnum.IS_DEL.NO.toString());
        List<CaseEntity> caseEntities = caseMapper.findByWhere(page,entity);
        List<CaseVO> caseVOs = MapToBean.toList(caseEntities,CaseVO.class);
        for(CaseVO caseVO: caseVOs){
            LesionEntity lesionEntity=new LesionEntity();
            lesionEntity.setCaseId(caseVO.getCaseId());
            lesionEntity.setIsDel(TypeEnum.IS_DEL.NO.toString());
            List<LesionEntity> lesionEntities = lesionMapper.findByWhere(lesionEntity);
            List<LesionVO> lesionVOs = MapToBean.toList(lesionEntities,LesionVO.class);
            caseVO.setLesionVOs(lesionVOs);
            List<ImageEntity> imageEntities = imageLogic.findImageByResourceId(caseVO.getCaseTitle());
            List<ImageVO> imageVOs = MapToBean.toList(imageEntities,ImageVO.class);
            List<ImageVO> caseImageVOs=new ArrayList<>();
            List<ImageVO> labelImageVOs=new ArrayList<>();
            for(ImageVO imageVO:imageVOs){
                if(imageVO.getResourceType().equals(TypeEnum.RESOURCE_TYPE.CASE.toString())){
                    caseImageVOs.add(imageVO);
                }else if(imageVO.getResourceType().equals(TypeEnum.RESOURCE_TYPE.LESION.toString())){
                    labelImageVOs.add(imageVO);
                }
            }
            caseVO.setCaseImageVO(caseImageVOs);
            caseVO.setLabelImage(labelImageVOs);
            MarkEntity markEntity = markMapper.findByUserIdAndCaseId(caseVO.getCaseId(),userId);
            if(markEntity!=null){
                caseVO.setIsMarked(markEntity.getIsDel());
            }else{
                caseVO.setIsMarked(TypeEnum.IS_MARKED.NO.toString());
            }
        }
        return caseVOs;
    }

    /**
     * 获取收藏病例列表
     */
    public List<CaseVO> findMarkList(Page<CaseVO> page,String userId){
        CaseEntity entity = new CaseEntity();
        entity.setCreatorId(userId);
        entity.setIsDel(TypeEnum.IS_DEL.NO.toString());
        List<CaseEntity> caseEntities = caseMapper.findMarkList(page,entity);
        List<CaseVO> caseVOs = MapToBean.toList(caseEntities,CaseVO.class);
        for(CaseVO caseVO: caseVOs){
            LesionEntity lesionEntity=new LesionEntity();
            lesionEntity.setCaseId(caseVO.getCaseId());
            lesionEntity.setIsDel(TypeEnum.IS_DEL.NO.toString());
            List<LesionEntity> lesionEntities = lesionMapper.findByWhere(lesionEntity);
            List<LesionVO> lesionVOs = MapToBean.toList(lesionEntities,LesionVO.class);
            caseVO.setLesionVOs(lesionVOs);
            List<ImageEntity> imageEntities = imageLogic.findImageByResourceId(caseVO.getCaseId());
            List<ImageVO> imageVOs = MapToBean.toList(imageEntities,ImageVO.class);
            List<ImageVO> caseImageVOs=new ArrayList<>();
            List<ImageVO> labelImageVOs=new ArrayList<>();
            for(ImageVO imageVO:imageVOs){
                if(imageVO.getResourceType().equals(TypeEnum.RESOURCE_TYPE.CASE.toString())){
                    caseImageVOs.add(imageVO);
                }else if(imageVO.getResourceType().equals(TypeEnum.RESOURCE_TYPE.LESION.toString())){
                    labelImageVOs.add(imageVO);
                }
            }
            caseVO.setCaseImageVO(caseImageVOs);
            caseVO.setLabelImage(labelImageVOs);
            caseVO.setIsMarked(TypeEnum.IS_MARKED.YES.toString());
        }
        return caseVOs;
    }

    /**
     * 获取病例详情
     */
    public CaseVO findCaseDetail(String caseId,String userId){
        CaseEntity entity = caseMapper.loadByKey(caseId);
        CaseVO caseVO = MapToBean.toBean(entity,CaseVO.class);

        LesionEntity lesionEntity=new LesionEntity();
        lesionEntity.setCaseId(caseId);
        lesionEntity.setIsDel(TypeEnum.IS_DEL.NO.toString());
        List<LesionEntity> lesionEntities = lesionMapper.findByWhere(lesionEntity);
        List<LesionVO> lesionVOs = MapToBean.toList(lesionEntities,LesionVO.class);
        caseVO.setLesionVOs(lesionVOs);
        List<ImageEntity> imageEntities = imageLogic.findImageByResourceId(entity.getCaseTitle());
        List<ImageVO> imageVOs = MapToBean.toList(imageEntities,ImageVO.class);
        List<ImageVO> caseImageVOs=new ArrayList<>();
        List<ImageVO> labelImageVOs=new ArrayList<>();
        for(ImageVO imageVO:imageVOs){
            if(imageVO.getResourceType().equals(TypeEnum.RESOURCE_TYPE.CASE.toString())){
                caseImageVOs.add(imageVO);
            }else if(imageVO.getResourceType().equals(TypeEnum.RESOURCE_TYPE.LESION.toString())){
                labelImageVOs.add(imageVO);
            }
        }
        caseVO.setCaseImageVO(caseImageVOs);
        caseVO.setLabelImage(labelImageVOs);
        MarkEntity markEntity = markMapper.findByUserIdAndCaseId(caseVO.getCaseId(),userId);
        if(markEntity!=null){
            if(markEntity.getIsDel().equals(TypeEnum.IS_DEL.NO.toString())){
                caseVO.setIsMarked(TypeEnum.IS_MARKED.NO.toString());
            }else{
                caseVO.setIsMarked(TypeEnum.IS_MARKED.YES.toString());
            }
        }else{
            caseVO.setIsMarked(TypeEnum.IS_MARKED.YES.toString());
        }
        return caseVO;
    }

    /**
     * 批量新增病例
     */
    @Transactional
    public List<String> saveCaseBatch(File file){
        List<String> result = new ArrayList<>();
        List<CaseVO> importList = new ArrayList<>();
        importList = readExcel(file);
        for(CaseVO caseVO:importList){
            List<LesionVO> lesionVOs=caseVO.getLesionVOs();
            CaseEntity entity = MapToBean.toBean(caseVO, CaseEntity.class);
            entity.setIsDel(TypeEnum.IS_DEL.NO.toString());
            caseMapper.insertCase(entity);
            lesionLogic.insertLesions(lesionVOs,null,entity.getCaseId());
            List<ImageVO> imageVOs = new ArrayList<>();
            ImageVO caseImgaeVO = new ImageVO();
            caseImgaeVO.setImageId(CommonUtils.getUUID());
            caseImgaeVO.setResourceType(TypeEnum.RESOURCE_TYPE.CASE.toString());
            imageVOs.add(caseImgaeVO);
            ImageVO lesionImgaeVO = new ImageVO();
            lesionImgaeVO.setImageId(CommonUtils.getUUID());
            lesionImgaeVO.setResourceType(TypeEnum.RESOURCE_TYPE.LESION.toString());
            imageVOs.add(lesionImgaeVO);
            imageLogic.saveImageInfo(imageVOs,null,entity.getCaseId(),entity.getCaseTitle());
            result.add(entity.getCaseId());
        }
        return result;
    }

    // 去读Excel的方法readExcel，该方法的入口参数为一个File对象
    // https://blog.csdn.net/qq_39740279/article/details/104398825
    public List<CaseVO> readExcel(File file) {
        try {
            // 创建输入流，读取Excel
            InputStream is = new FileInputStream(file.getAbsolutePath());
            // jxl提供的Workbook类
            Workbook wb = Workbook.getWorkbook(is);
            // 只使用第一个sheet页
            int sheet_size = 0;
//            int sheet_size = wb.getNumberOfSheets();
            List<CaseVO> outerList=new ArrayList<>();
            // 每个页签创建一个Sheet对象
            Sheet sheet = wb.getSheet(sheet_size);
            // sheet.getRows()返回该页的总行数
            for (int i = 2; i < sheet.getRows(); i++) {
                List innerList=new ArrayList();
                CaseVO caseVO = new CaseVO();
                String caseTitle = sheet.getCell(0, i).getContents();
                if(caseTitle == null || caseTitle == ""){
                    break;
                }
                caseVO.setCaseId(CommonUtils.getUUID());
                caseVO.setCaseTitle(caseTitle);
                caseVO.setPatientGender(sheet.getCell(1, i).getContents());
                caseVO.setPatientAge(sheet.getCell(2, i).getContents());
                caseVO.setClinical(sheet.getCell(3, i).getContents());
                caseVO.setClinicalHistory(sheet.getCell(4, i).getContents());
                caseVO.setMachine(sheet.getCell(5, i).getContents());
                caseVO.setTracer(sheet.getCell(6, i).getContents());
                caseVO.setDiagnosis(sheet.getCell(7, i).getContents());
                String lesions = sheet.getCell(8, i).getContents();
                String[] lesionList = lesions.split("；");
                List<LesionVO> lesionVOs = new ArrayList<>();
                for(int j=0;j<lesionList.length;j++){
                    LesionVO lesionVO = new LesionVO();
                    String[] ls = lesionList[j].split("，");
                    lesionVO.setLesionLocation(ls[0]);
                    lesionVO.setLesionInfo(ls[1]);
                    lesionVOs.add(lesionVO);
                }
                caseVO.setLesionVOs(lesionVOs);
                caseVO.setOpinion(sheet.getCell(9, i).getContents());
                outerList.add(caseVO);
            }
            return outerList;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (BiffException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
